/**
 * 用户模块
 */

const { _ } = require('lodash');

const Router = require('koa-router');
const { system } = require('../conf/tables');
module.exports = (app) => {
    const router = new Router({
        prefix: '/user'
    })

    router.get('/menu', async(ctx, next) => {
        const functions = await app.context.knex(system.endPoint).where({ enable: '1' }).orderBy('od');
        ctx.body = functions.filter((fn) => {
            //查看用户的级别是否在排除的范围
            let ucan = true;
            if (fn.exclude) {
                ucan = _.values(JSON.parse(fn.exclude)).indexOf(parseInt(ctx.state.user.level)) < 0;
            }
            //可能还要加入更多的过滤，比如某些条件下才可以现实

            //当前用户是否有权限访问此菜单
            return ucan && parseInt(fn.level, 2) & parseInt(ctx.state.user.level, 2);

        })
    });

    router.get('/curr', async(ctx, next) => {
        ctx.body = ctx.state.user;
    });

    /**
     * 更新登录用户的密码
     */
    router.post('/password/update', async(ctx, next) => {
        const { sp_pwd = 0, sp_upt = '123456' } = ctx.request.fields;
        const { user } = ctx.state;
        ctx.body = user.pwd === sp_pwd ? await app.context.knex(system.saveUserinfo) .where({ id: user.id }) .update({ pwd: sp_upt }) : 0;
    });

    app.use(router.routes())
        .use(router.allowedMethods());
}